<?php
// 应用公共文件
use think\facade\Db;

/**
 * 递归获取菜单
 */

function children_menu($info = false, $list, $pid = 0)
{
    $arr = [];
    foreach ($list as $k => $v) {
        //当前模块id为打开模块父id时 || 或者当前模块name为打开模块name时 赋值当前模块active为真
        if ($info) {
            if ($v['id'] == $info['pid'] || $v['url'] == $info['url']) {
                $v['active'] = 1;
            }
        } else {
            $v['active'] = 0;
        }
        //当前模块pid为传入根pid相等时调用递归获取当前模块的子模块
        if ($v['pid'] == $pid) {
            //调用递归
            $v['children'] = children_menu($info, $list, $v['id']);
            //获取子模块列表所有的active,  当子模块中有active为真时 赋值当前模块active为真
            if (in_array(1, array_column($v['children'], 'active'))) {
                $v['active'] = 1;
            }
            if (!isset($v['active'])) {
                $v['active'] = 0;
            }
            $arr[] = $v;
        }
    }
    //返回递归后的数据
    return $arr;
}


function menu_path($list, $id)
{
    $arr = [];
    foreach ($list as $k => $v) {
        if ($v['id'] == $id) {

            $arr[] = $v;
            $arr = array_merge($arr, menu_path($list, $v['pid']));
        }
    }
    return $arr;
}

function children_name($list, $key, $pid = 0, $level = 0)
{
    $arr = [];
    foreach ($list as $v) {
        if ($v['pid'] != $pid) continue;
        $v[$key] = str_repeat('|——', $level) . $v[$key];
        $arr[] = $v;
        $arr = array_merge($arr, children_name($list, $key, $v['id'], $level + 1));
    }
    return $arr;
}

function children_ids($list, $pid, $thisid = false)
{
    $arr = [];
    foreach ($list as $v) {
        if ($v['pid'] == $pid) {
            $arr[] = $v['id'];
            $arr = array_merge($arr, children_ids($list, $v['id']));
        }
    }
    if ($thisid === true)
        $arr[] = $pid;
    return array_unique($arr);
}

/**
 * 导入SQL
 *
 * @param   string $sqlFile sql文件路面
 * @param   string $sql_path 表前缀
 * @return  boolean
 */
function importsql($sqlFile, $prefix = '')
{
    if (is_file($sqlFile)) {
        $lines = file($sqlFile);
        $templine = '';
        foreach ($lines as $line) {
            if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*')
                continue;

            $templine .= $line;
            if (substr(trim($line), -1, 1) == ';') {
                $templine = str_ireplace('jsu_', $prefix, $templine);
                $templine = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $templine);
                try {
                    Db::execute($templine);
                } catch (\PDOException $e) {
                    throw new \Exception($e->getMessage());
                }
                $templine = '';
            }
        }
    }
    return true;
}

/**
 * 判断 文件/目录 是否可写（取代系统自带的 is_writeable 函数）
 * @param string $file 文件/目录
 * @return boolean
 */
function new_is_writeable($file)
{
    if (is_dir($file)) {
        $dir = $file;
        if ($fp = @fopen("$dir/test.txt", 'w')) {
            @fclose($fp);
            @unlink("$dir/test.txt");
            $writeable = true;
        } else {
            $writeable = false;
        }
    } else {
        if ($fp = @fopen($file, 'a+')) {
            @fclose($fp);
            $writeable = true;
        } else {
            $writeable = false;
        }
    }

    return $writeable;
}


function curl($url, $data = '', $style = '', $headers = [])
{
    if ($style) {
        $headers[] = 'Content-Type: application/' . $style . '; charset=utf-8';
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
    }
    $curl = curl_init();
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0");
    if (strstr($url, 'https://')) {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, 60);
    $result = curl_exec($curl);
    $error = curl_error($curl);
    $output = $error ? $error : $result;
    return $output;
}

/**
 * 压缩文件
 * @param array $files 待压缩文件 array('d:/test/1.txt'，'d:/test/2.jpg');【文件地址为绝对路径】
 * @param string $filePath 输出文件路径 【绝对文件地址】 如 d:/test/new.zip
 * @return string|bool
 */
function zip($files, $filePath)
{
    //检查参数
    if (empty($files) || empty($filePath)) {
        return false;
    }

    //压缩文件
    $zip = new ZipArchive();
    $zip->open($filePath, ZipArchive::CREATE);
    foreach ($files as $key => $file) {
        //检查文件是否存在
        if (!file_exists($file)) {
            return false;
        }
        $zip->addFile($file, basename($file));
    }
    $zip->close();

    return true;
}

/**
 * zip解压方法
 * @param string $filePath 压缩包所在地址 【绝对文件地址】d:/test/123.zip
 * @param string $path 解压路径 【绝对文件目录路径】d:/test
 * @return bool
 */
function unzip($filePath, $path)
{
    if (empty($path) || empty($filePath)) {
        return false;
    }

    $zip = new ZipArchive();

    if ($zip->open($filePath) === true) {
        $zip->extractTo($path);
        $zip->close();
        return true;
    } else {
        return false;
    }
}
function isMobile()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset($_SERVER['HTTP_VIA'])) {
        //找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    //判断手机发送的客户端标志,兼容性有待提高
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array(
            'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-',
            'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian',
            'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    //协议法，因为有可能不准确，放到最后判断
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false)
            && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false ||
                (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') <
                    strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))
        ) {
            return true;
        }
    }
    return false;
}

function is_weixin()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}
